#import "MainPageUI.h"
#import "zhaopinViewController.h"
#import "JobListUI.h"
#import "SGFocusImageFrame.h"
#import "SGFocusImageItem.h"
#import "FujinYDViewController.h"
#import "mingxingPDViewController.h"
#import "fujinActViewController.h"
#import "qiuzhiViewController.h"
#import "searchPageViewController.h"
@interface MainPageUI ()

@end

@implementation MainPageUI

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
       
    }
    return self;
}
-(void)ershoushebeiFn{
    ErshoushebeiListUI*  ui=[[ErshoushebeiListUI alloc] init];
    ui.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:ui animated:YES];
}

-(void)trouseFn{
    TrouseListUI*  ui=[[TrouseListUI alloc] init];
    ui.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:ui animated:YES];
}
-(void)trainingFn{
    TrainingListUI*  ui=[[TrainingListUI alloc] init];
    ui.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:ui animated:YES];
}
-(void)maganeFn{
    ManageListUI*  ui=[[ManageListUI alloc] init];
    ui.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:ui animated:YES];
}





-(void)paiduiFn{
    mingxingPDViewController* ui=[[mingxingPDViewController alloc] init];
    ui.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:ui animated:YES];
}

-(void)nearbyMerchantFn{
    //NearbyMerchantUI* ui=[[NearbyMerchantUI alloc] init];
    FujinYDViewController *ui = [FujinYDViewController new];
    ui.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:ui animated:YES];
}
-(void)recruitModuleFm{
    zhaopinViewController* ui=[[zhaopinViewController alloc] init];
    ui.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:ui animated:NO];
}
-(void)jobsFm{
    qiuzhiViewController* ui=[[qiuzhiViewController alloc] init];
    ui.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:ui animated:NO];
}
-(void)merchantRankListFm{
    MerchantRankListUI* ui=[[MerchantRankListUI alloc] init];
    ui.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:ui animated:NO];
}
-(void)nearbyActivityFm{
    fujinActViewController*  ui=[[fujinActViewController alloc] init];
    ui.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:ui animated:NO];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    // 获取经纬度
    NSLog(@"纬度:%f",newLocation.coordinate.latitude);
    NSLog(@"经度:%f",newLocation.coordinate.longitude);
    
    // 停止位置更新
    [manager stopUpdatingLocation];
    longitude=newLocation.coordinate.longitude;
    latitude=newLocation.coordinate.latitude;
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSString* uid=[ud objectForKey:@"uid"];
    NSLog(@"updatePosFn进来.uid=%@",uid);
    [ud setValue:[NSString stringWithFormat:@"%f",longitude] forKey:@"longitude"];
    [ud setValue:[NSString stringWithFormat:@"%f",latitude] forKey:@"latitude"];
    if (updatePos&&uid) {
        NSLog(@"updatePosFn进来");
        updatePos=NO;
         [NSThread detachNewThreadSelector:@selector(updatePosFn) toTarget:self withObject:nil];
    }
}
-(void)updatePosFn{
    NSString* loginURL=HOST;
    loginURL=[loginURL stringByAppendingString:@"index.php/appI/updatePos"];
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    
    NSUserDefaults* ud=[[NSUserDefaults alloc] init];
    NSString* uid=[ud objectForKey:@"uid"];
    
    [req addPostValue:[NSString stringWithFormat:@"%@",uid] forKey:@"uid"];
    [req addPostValue:[NSString stringWithFormat:@"%f",longitude] forKey:@"longi"];
    [req addPostValue:[NSString stringWithFormat:@"%f",latitude] forKey:@"latitude"];
    
    [req startSynchronous];
    NSError *error = [req error];
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        NSString *response = [req responseString];
        //NSLog(@"返回结果..%@",response);
        
        
    }

}

// 定位失误时触发
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"error:%@",error);
}
 
-(void)loadFocusFn{
    NSString* url=[HOST stringByAppendingString:@"index.php/AppLoginUser/updateLastLogin"];
    NSError *error;
    NSString *jsonStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error:&error];
    //NSLog(@"jsonStr===%@",jsonStr);
   
    focusList=[NSArray arrayWithArray:[jsonStr JSONValue]];
    [self performSelectorOnMainThread:@selector(finishLoadFocusFn) withObject:nil waitUntilDone:YES];
}
-(void)finishLoadFocusFn{
    int length = focusList.count;
    NSMutableArray *tempArray = [NSMutableArray array];
    
    NSString*  url1=@"";
    for (int i = 0 ; i < length; i++)
    {
        NSDictionary* dic=[focusList objectAtIndex:i];
        //NSLog(@"dic==%@",dic);
        NSString*  url=[dic objectForKey:@"url"];
        NSString* image=[HOST stringByAppendingString:url];
        if (i==0) {
            url1=image;
        }
        
        
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"title%d",i],@"title" ,image,@"image",nil];
        
        
        
        [tempArray addObject:dict];
    }
    
    NSMutableArray *itemArray = [NSMutableArray arrayWithCapacity:length+2];
    
    if (length > 1)
    {
        NSDictionary *dict = [tempArray objectAtIndex:length-1];
        SGFocusImageItem *item = [[SGFocusImageItem alloc] initWithDict:dict tag:-1];
        item.image=url1;
        
        [itemArray addObject:item];
    }
    for (int i = 0; i < length; i++)
    {
        NSDictionary *dict = [tempArray objectAtIndex:i];
        SGFocusImageItem *item = [[SGFocusImageItem alloc] initWithDict:dict tag:i];
        item.image=url1;
        
        [itemArray addObject:item];
        
    }
    //添加第一张图 用于循环
    if (length >1)
    {
        NSDictionary *dict = [tempArray objectAtIndex:0];
        SGFocusImageItem *item = [[SGFocusImageItem alloc] initWithDict:dict tag:length];
        item.image=url1;
        [itemArray addObject:item];
    }
    SGFocusImageFrame *bannerView = [[SGFocusImageFrame alloc] initWithFrame:CGRectMake(0, 0, 320, 180) delegate:self imageItems:itemArray isAuto:YES];
    [bannerView scrollToIndex:2];
    [_scroll addSubview:bannerView];

}
-(void)sendLinkContent{
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [app sendImageContent];
}

-(void)refreshCompanyListFn:(NSNotification*)aNSNotification{
    NSDictionary*  dic=aNSNotification.object;
    NSString* cityName=dic[@"cityName"];
    //NSLog(@"cityName====%@",cityName);
    cityName=[cityName stringByAppendingString:@"▼"];
    [cityBtn setTitle:cityName forState:0];
    cityBtn.tintColor=[UIColor whiteColor];
}
/////

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    CLLocation *currentLocation = [locations lastObject];
    

    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     {
         if (array.count > 0)
         {
             CLPlacemark *placemark = [array objectAtIndex:0];
             
             //将获得的所有信息显示到label上
             //self.location.text = placemark.name;
             
             NSString *city = placemark.locality;
             if (!city) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 city = placemark.administrativeArea;
             }
             
             
             city = [city stringByReplacingOccurrencesOfString:@"市" withString:@""];
             city=[city stringByAppendingString:@"▼"];
             [cityBtn setTitle:city forState:UIControlStateNormal];
             
             
         }
         else if (error == nil && array.count ==0) {
             NSLog(@"定位不到当前城市");
         }
         else if (error != nil) {
             NSLog(@"出现错误  %@",error);
         }
     }];

    
    [self.locationManager stopUpdatingLocation];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.tintColor=[UIColor blackColor];
    [NSThread detachNewThreadSelector:@selector(loadFocusFn) toTarget:self withObject:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshCompanyListFn:) name:@"refreshCompanyListFn" object:nil];
    
    updatePos=YES;
    
    
    
    
    //老王测试经纬度:
//    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
//    [ud setValue:@"121.726162" forKey:@"longitude"];
//    [ud setValue:@"31.27261892" forKey:@"latitude"];
    
    
    self.locationManager = [[CLLocationManager alloc] init];
    
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 10.0f;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
        NSLog(@"requestAlwaysAuthorization....");
        [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager startUpdatingLocation];
    }else{
        [self.locationManager startUpdatingLocation];
    }
    
   

  
    
    NSArray *itemArr = self.tabBarController.tabBar.items;
    for (int i = 0;i<itemArr.count;i++) {
        UITabBarItem *item = itemArr[i];
        //UIImage *selectedImage = [UIImage imageNamed:[NSString stringWithFormat:@"menu%i_focus",i]];
        //UIImage *unselectedImage = [UIImage imageNamed:[NSString stringWithFormat:@"menu%i",i]];
        
        
        
        UIImage * selectedImage = [[UIImage imageNamed:[NSString stringWithFormat:@"menu%i_focus",i]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        
        UIImage * unselectedImage = [[UIImage imageNamed:[NSString stringWithFormat:@"menu%i",i]]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        
        
        
        [item setFinishedSelectedImage:selectedImage
           withFinishedUnselectedImage:unselectedImage];
    }
    
    AppDelegate *app = [[UIApplication sharedApplication] delegate];
    [app loginStateChange:nil];
 
    
    [_scroll setContentSize:CGSizeMake(self.view.frame.size.width,455+1)];
    
  
    
     [_nearbyMerchantBtn addTarget:self action:@selector(nearbyMerchantFn) forControlEvents:UIControlEventTouchUpInside];
    
    
    [_recruitBtn addTarget:self action:@selector(recruitModuleFm) forControlEvents:UIControlEventTouchUpInside];
    //
    UIImageView*  recruitIv=[[UIImageView  alloc] initWithFrame:CGRectMake(0, 60, _recruitBtn.frame.size.width, 20)];
    [recruitIv setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.6f]];
    
    [_recruitBtn addSubview:recruitIv];
    
    
    UILabel*  recruitLb=[[UILabel  alloc] initWithFrame:CGRectMake(0,60, recruitIv.frame.size.width, 20)];
    recruitLb.textColor=[UIColor whiteColor];
    recruitLb.text=@"夜店招聘";
    recruitLb.font=[UIFont systemFontOfSize:12];
    recruitLb.textAlignment=NSTextAlignmentCenter;
    [_recruitBtn addSubview:recruitLb];
    
    
    UIImageView*  jobIv=[[UIImageView  alloc] initWithFrame:CGRectMake(0, 60, _jobBtn.frame.size.width, 20)];
    [jobIv setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.6f]];
    
    [_jobBtn addSubview:jobIv];
    //
    UILabel*  jobLb=[[UILabel  alloc] initWithFrame:CGRectMake(0,60, jobIv.frame.size.width, 20)];
    jobLb.textColor=[UIColor whiteColor];
    jobLb.text=@"夜店求职";
    jobLb.font=[UIFont systemFontOfSize:12];
    jobLb.textAlignment=NSTextAlignmentCenter;
    [_jobBtn addSubview:jobLb];
    
    
    [_jobBtn addTarget:self action:@selector(jobsFm) forControlEvents:UIControlEventTouchUpInside];
    
    //
    UIImageView*  paimingIv=[[UIImageView  alloc] initWithFrame:CGRectMake(0, 60, _rankBtn.frame.size.width-20, 20)];
    [paimingIv setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.6f]];
    
    [_rankBtn addSubview:paimingIv];
    //
    UILabel*  paimingLb=[[UILabel  alloc] initWithFrame:CGRectMake(10,60, paimingIv.frame.size.width, 20)];
    paimingLb.textColor=[UIColor whiteColor];
    paimingLb.text=@"夜店排名";
    paimingLb.font=[UIFont systemFontOfSize:12];
    paimingLb.textAlignment=NSTextAlignmentCenter;
    [_rankBtn addSubview:paimingLb];

    
    
    [_paiduiBtn addTarget:self action:@selector(paiduiFn) forControlEvents:UIControlEventTouchUpInside];
    
    /////////
    UIImageView*  activityIv=[[UIImageView  alloc] initWithFrame:CGRectMake(0, 60, _activityBtn.frame.size.width, 20)];
    [activityIv setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.6f]];
    
    [_activityBtn addSubview:activityIv];
    //
    UILabel*  activityLb=[[UILabel  alloc] initWithFrame:CGRectMake(0,60, activityIv.frame.size.width, 20)];
    activityLb.textColor=[UIColor whiteColor];
    activityLb.text=@"附近活动";
    activityLb.font=[UIFont systemFontOfSize:12];
    activityLb.textAlignment=NSTextAlignmentCenter;
    [_activityBtn addSubview:activityLb];

    
    
    [_activityBtn addTarget:self action:@selector(nearbyActivityFm) forControlEvents:UIControlEventTouchUpInside];
    
    [_jobBtn addTarget:self action:@selector(jobsFm) forControlEvents:UIControlEventTouchUpInside];
    [_rankBtn addTarget:self action:@selector(merchantRankListFm) forControlEvents:UIControlEventTouchUpInside];
    
    [_ershoushebeiBtn addTarget:self action:@selector(ershoushebeiFn) forControlEvents:UIControlEventTouchUpInside];
    
    
    [_trouseBtn addTarget:self action:@selector(trouseFn) forControlEvents:UIControlEventTouchUpInside];
    
    
    [_trainingBtn addTarget:self action:@selector(trainingFn) forControlEvents:UIControlEventTouchUpInside];
    
    [_manageBtn addTarget:self action:@selector(maganeFn) forControlEvents:UIControlEventTouchUpInside];
    //
    UIImageView*  nearbyMerchantIv=[[UIImageView  alloc] initWithFrame:CGRectMake(0, 60, _nearbyMerchantBtn.frame.size.width, 20)];
    [nearbyMerchantIv setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.6f]];
    
    [_nearbyMerchantBtn addSubview:nearbyMerchantIv];
    //
    UILabel*  nearbyMerchantLb=[[UILabel  alloc] initWithFrame:CGRectMake(0,60, activityIv.frame.size.width, 20)];
    nearbyMerchantLb.textColor=[UIColor whiteColor];
    nearbyMerchantLb.text=@"附近夜店";
    nearbyMerchantLb.font=[UIFont systemFontOfSize:12];
    nearbyMerchantLb.textAlignment=NSTextAlignmentCenter;
    [_nearbyMerchantBtn addSubview:nearbyMerchantLb];
    ////////
    
    
    UIImageView*  paiduiIv=[[UIImageView  alloc] initWithFrame:CGRectMake(0, 60, _nearbyMerchantBtn.frame.size.width, 20)];
    [paiduiIv setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.6f]];
    
    [_paiduiBtn addSubview:paiduiIv];
    //
    UILabel*  paiduiLb=[[UILabel  alloc] initWithFrame:CGRectMake(0,60, activityIv.frame.size.width, 20)];
    paiduiLb.textColor=[UIColor whiteColor];
    paiduiLb.text=@"明星派对";
    paiduiLb.font=[UIFont systemFontOfSize:12];
    paiduiLb.textAlignment=NSTextAlignmentCenter;
    [_paiduiBtn addSubview:paiduiLb];
    
    //
    UIImageView*  videoTitleIv=[[UIImageView  alloc] initWithFrame:CGRectMake(0, 0, _videoIv.frame.size.width, 30)];
    [videoTitleIv setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.6f]];
    
    [_videoIv addSubview:videoTitleIv];
    //
    UILabel*  newLb=[[UILabel  alloc] initWithFrame:CGRectMake(10, 5, 60, 20)];
    newLb.text=@"NEW";
    newLb.font=[UIFont systemFontOfSize:12];
    newLb.textColor=[UIColor colorWithHexString:@"#ed1e23"];
    [videoTitleIv addSubview:newLb];
    //
    UILabel*  videoLb=[[UILabel  alloc] initWithFrame:CGRectMake(48, 5, 60, 20)];
    videoLb.text=@"视屏秀";
    videoLb.font=[UIFont systemFontOfSize:12];
    videoLb.textColor=[UIColor whiteColor];
    [videoTitleIv addSubview:videoLb];
    
    //
    UIButton*  searchBtn=[[UIButton alloc] initWithFrame:CGRectMake(20, 5, 220, 30)];
    searchBtn.backgroundColor=[UIColor whiteColor];
    searchBtn.layer.borderColor=[UIColor lightGrayColor].CGColor;
    searchBtn.layer.cornerRadius=3.0;
    [searchBtn addTarget:self action:@selector(searchEvent) forControlEvents:UIControlEventTouchUpInside];
    //
    UILabel*  lb=[[UILabel  alloc] initWithFrame:CGRectMake(5, 5, 220,20)];
    lb.text=@"夜店/招聘/求职";
    lb.font=[UIFont systemFontOfSize:13];
    lb.textColor=[UIColor lightGrayColor];
    lb.textAlignment=NSTextAlignmentLeft;
    [searchBtn addSubview:lb];
    //
    UIImageView*  searchIv=[[UIImageView alloc] initWithFrame:CGRectMake(180, 2.5, 25, 25)];
    searchIv.image=[UIImage imageNamed:@"home_search_btn_released"];
    [searchBtn addSubview:searchIv];
    
    
    UIBarButtonItem* bar=[[UIBarButtonItem  alloc] initWithCustomView:searchBtn];
    
   
    
    
    self.navigationItem.leftBarButtonItem=bar;
    //VideoShowViewController
    
    _videoIv.userInteractionEnabled=YES;
    UITapGestureRecognizer *singleTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonpress1:)];
    [_videoIv addGestureRecognizer:singleTap1];
    

    
}

-(void)searchEvent{
    searchPageViewController *vc = [searchPageViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)buttonpress1:(id)sender{
    VideoShowViewController* ui=[[VideoShowViewController alloc] init];
    ui.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:ui animated:NO];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}


- (IBAction)cityListFn:(id)sender {
    CityListViewController *ui = [[CityListViewController alloc] initWithNibName:@"CityListViewController" bundle:nil];
    ui.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:ui animated:NO];
    
        //[self presentModalViewController:ui animated:NO];
     
}

- (IBAction)shareFn:(id)sender {
    NSLog(@"开始分享....");
    AppDelegate *appDelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    [appDelegate sendLinkContent];
}
@end
